package pers.wq.util;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Helper {

	public static String json_encode(Map<String,Object> map){
		StringBuilder sb = new StringBuilder();
		Iterator<String> iterator = map.keySet().iterator();
		String key;
		sb.append("{");
		while(iterator.hasNext()){
			key = iterator.next();
			if(null == map.get(key)){
				sb.append("\"" + key + "\"" + ":\"null\",");
			}else if(map.get(key) instanceof Map){
				sb.append("\"" + key + "\":" +  json_encode((Map)map.get(key)) + ",");
			}else if(map.get(key) instanceof List){
				sb.append("\"" + key + "\":" + json_encode((List)map.get(key)) + ",");
			}else{
				sb.append("\"" + key + "\"" + ":\"" + map.get(key).toString() + "\",");
			}
		}
		if(sb.charAt(sb.length()-1) == ','){
			sb = sb.deleteCharAt(sb.length()-1);
		}
		sb.append("}");
		return sb.toString();
	}
	
	public static String json_encode(List<Object> listMap){
		StringBuilder sb = new StringBuilder();
		Iterator<Object> iterator = listMap.iterator();
		Object obj;
		sb.append("[");
		while(iterator.hasNext()){
			obj = iterator.next();
			if(obj instanceof Map){
				sb.append(json_encode((Map)obj) + ",");
			}else if(obj instanceof List){
				sb.append(json_encode((List)obj) + ",");
			}
		}
		if(sb.charAt(sb.length()-1) == ','){
			sb = sb.deleteCharAt(sb.length()-1);
		}
		sb.append("]");
		return sb.toString();
	}
	
	public static boolean strIsNull(String str){
		if(null == str || str.equals("")){
			return true;
		}
		return false;
	}
	
	 public static String encodeUnicode(String source){  
	        StringBuffer sb = new StringBuffer();  
	        char [] source_char = source.toCharArray();  
	        String unicode = null;  
	        for (int i=0;i<source_char.length;i++) {  
	            unicode = Integer.toHexString(source_char[i]);  
	            if (unicode.length() <= 2) {  
	                unicode = "00" + unicode;  
	            }  
	            sb.append("\\u" + unicode);  
	        }  
	        System.out.println(sb);  
	        return sb.toString();  
	    }  
	
	public static String decodeUnicode(String unicode) {       
        StringBuffer sb = new StringBuffer();  
            
        String[] hex = unicode.split("\\\\u");  
        
        for (int i = 1; i < hex.length; i++) {  
            int data = Integer.parseInt(hex[i], 16);  
            sb.append((char) data);  
        }  
        return sb.toString();    
     }   
}
